package com.dyz.wsw.common.utils.security;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

/**
 * RSA加解密
 * @author dyz
 * Time 2024/6/26 22:18
 */
public class RSA {

    /**
     *
     * @param encryptedString 公钥加密后的密文
     * @param base64PrivateKey base64编码后的私钥
     * @return 解出的明文
     * @throws Exception 解密时的异常
     */
    public static String decrypt(String encryptedString,String base64PrivateKey) throws Exception{
        PrivateKey privateKey = getPrivateKey(base64PrivateKey);
        //初始化 Cipher
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE,privateKey);
        //解码加密的字符串
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedString);
        //解密
        byte[] decryptedBytes  = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }


    /**
     * 将Base64编码后的私钥还原成PrivateKey
     * @return PrivateKey
     */
    public static PrivateKey getPrivateKey(String base64PrivateKey) throws Exception {
        //解码私钥字符串
        byte[] decode = Base64.getDecoder().decode(base64PrivateKey);
        //加载私钥
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decode);
        return keyFactory.generatePrivate(keySpec);
    }
}
